/**
 * Copyright � 2012 GestureSoft. ALL RIGHTS RESERVED.
 * This file contains proprietary and GestureSoft CONFIDENTIAL Information.
 * Use, disclosure or reproduction is prohibited.
 * 
 * @fileName ThemeManager.as
 * @creationDate Aug 8, 2012
 * @author 
 * @version 1.0
 */
package com.gesturesoft.imultimax.model.thememanger
{
	import com.gesturesoft.imultimax.model.DataBaseManager;
	import com.gesturesoft.imultimax.model.error.DataBaseError;
	import com.gesturesoft.imultimax.model.interfaces.IDatabaseManager;
	import com.gesturesoft.imultimax.model.thememanger.interfaces.IThemeManager;
	import com.gesturesoft.imultimax.model.thememanger.xmlparser.ThemeParser;
	import com.gesturesoft.imultimax.model.vo.ThemeDetailVO;
	import com.gesturesoft.imultimax.model.vo.ThemeVO;
	import com.gesturesoft.imultimax.model.vo.ThemeVO1;
	
	import mx.collections.ArrayCollection;

	public class ThemeManager implements IThemeManager
	{
		
		private var _localThemeVersion:String;
		private var _serverThemeVersion:String;
		
		public function checkThemeVersion(serverThemeVersion:String):Boolean
		{
			
			var query:String;
			var iDataBaseManger:IDatabaseManager = new DataBaseManager();
			var localThemeVersion:String;
			var versionChanged:Boolean = false;
			var arrTheme:ArrayCollection;
			
			var serverThmeVertion:String = serverThemeVersion;
			
			
			query = "SELECT theme_version FROM THEME_VERSION WHERE theme_version='"+serverThemeVersion+"'";
			
			try
			{
				
				arrTheme = iDataBaseManger.getData( query );
				
			} 
			catch(error:DataBaseError) 
			{
				
				throw error;
				trace("error  -> ThemeManger.checkThemeVersion()");
				
			}
			
			if(arrTheme.length > 0)
			{
				
				if(serverThmeVertion != arrTheme[0].theme_version )
				{
					serverThemeVersion = serverThmeVertion;
					versionChanged = true;
				}
					
				
			}
			else
			{
				
				serverThemeVersion = serverThmeVertion;
				versionChanged = true;
				
			}
			
			return versionChanged;
			
		}
		
		/**
		 * Add user created theme details to THEMES table
		 */ 
		public function addTheme(theme:ThemeVO1):void
		{
			
			var dataBaseManger:IDatabaseManager = new DataBaseManager();
			var query:String = "INSERT INTO THEMES ( primary_color, secondary_color, label_color, active, creator, th_secondary_label_color, th_background ) " + 
						"VALUES('"+ 
						theme.primaryColor +"','" + 
						theme.secondaryColor +"','" + 
						theme.lableColor +"','" +
						theme.active+"','" +
						theme.creator+"','" +
						theme.secondaryLabelColor+"','" +
						theme.background+"')";
			
			executeHandler( query, dataBaseManger );
			
			addActiveTheme( theme );
			
		}
		
		/**
		 *  Add user created theme details to ACTIVE_THEME table
		 */ 
		public function addActiveTheme( theme:ThemeVO1 ):void
		{
			
			var query:String;
			var dataBaseManger:IDatabaseManager = new DataBaseManager();
			
			query = "DELETE FROM ACTIVE_THEME";
			executeHandler( query,  dataBaseManger);
			
			query = "INSERT INTO ACTIVE_THEME ( primary_color, secondary_color, label_color, at_secondary_label_color, at_background ) " + 
				"VALUES('"+ 
				theme.primaryColor +"','" + 
				theme.secondaryColor +"','" + 
				theme.lableColor +"','" +
				theme.secondaryLabelColor+"','" +
				theme.background+"')";
			
			executeHandler( query, dataBaseManger );
			
		}
		
		public function insertThemeVersion(val:String):void
		{
			
			var dataBaseManger:IDatabaseManager = new DataBaseManager();
			var arrResult:ArrayCollection = new ArrayCollection();
			var query:String;
			
			arrResult = retrieveHandler("SELECT * FROM THEME_VERSION");
			
			if(arrResult.length > 0)
			{
				executeHandler("DELETE FROM THEME_VERSION", dataBaseManger );
			}
			
			query = "INSERT INTO THEME_VERSION ( theme_version ) " + 
				"VALUES('"+val+"')"; 
			
			executeHandler( query, dataBaseManger );
			
		}
		
		/**
		 * Get parsed XML as array collection 
		 * Insert it into database
		 */ 
		public function process(themes:XML, themeVersion:String):void
		{
			
			var arrParsedTheme:ArrayCollection = new ArrayCollection();
			arrParsedTheme = ThemeParser.parse( themes );
			var iDataBaseManger:IDatabaseManager;
			
			iDataBaseManger = new DataBaseManager();
			
			if( isThemesExist() )//Means themes version changed so it first delete contents then enter new values
			{
				
				var deleteThemesQuery:String;
				
				iDataBaseManger.setTransactionStartPoint();
				//var delRecordID:int = int( retrieveHandler("SELECT th_id FROM IM_THEMES  WHERE creator='admin'")[0].th_id );
				
				deleteThemesQuery = "DELETE FROM IM_THEME_DETAILS WHERE td_id IN( SELECT th_id FROM IM_THEMES  WHERE creator='admin' )";
				
				try
				{
					iDataBaseManger.execute( deleteThemesQuery );
				} 
				catch(error:DataBaseError) 
				{
					
					iDataBaseManger.rollBackTransactions();
					trace("error  -> ThemeManger.process()");
					throw error;
					
				}
				
				deleteThemesQuery = "DELETE FROM IM_THEMES WHERE creator='admin'";
				
				try
				{
					iDataBaseManger.execute( deleteThemesQuery );
				} 
				catch(error:DataBaseError) 
				{
					
					iDataBaseManger.rollBackTransactions();
					trace("error  -> ThemeManger.process()");
					throw error;
					
				}
				
				
				iDataBaseManger.commitTransaction();
			}
			
			//iDataBaseManger.setTransactionStartPoint();
			insertThemes( arrParsedTheme, iDataBaseManger );
			//iDataBaseManger.commitTransaction();
			
			//Inserting theme version 
			insertThemeVersion(themeVersion);
			
		}
		
		/**
		 * @Return active theme details
		 */ 
		private function getActiveTheme( themes:ArrayCollection ):ThemeVO1
		{
			
			var activeTheme:ThemeVO1;
			
			for each( var theme:ThemeVO1 in themes )
			{
				
				if( theme.active.toLowerCase() == "true" )
				{
					
					activeTheme = theme;
					break;
				}
				
			}
			
			return activeTheme;
			
		}
		
		/**
		 * Insert themes to THEMES table
		 */ 
		public function insertThemes( themes:ArrayCollection, iDataBaseManager:IDatabaseManager ):void
		{
			
			var query:String;
			
			//iDataBaseManager.setTransactionStartPoint();
			
			for each(var themeVO:ThemeVO in themes)
			{
				
				var arrThemeDetail:ArrayCollection = new ArrayCollection(); 
				arrThemeDetail = themeVO.arrThemeDetailVO;
				
				query = "INSERT INTO IM_THEMES ( th_name, th_active, th_creator ) " + 
					    "VALUES('"+ 
						themeVO.name +"','" + 
						themeVO.active +"','" + 
						themeVO.creator +"')";
				executeHandler(query, iDataBaseManager);
				
				var themeID:int = int( retrieveHandler("SELECT last_insert_rowid() as ID", iDataBaseManager)[0].ID );

				//Inserting details for the primary color, secondary color,
				//primary text, secondary text
				for each(var themeDetailVO:ThemeDetailVO in arrThemeDetail)
				{
					
					query = "INSERT INTO IM_THEME_DETAILS ( property_name, value, gradient1, gradient2, stroke, text_color, td_id ) " + 
						"VALUES('"+ 
						themeDetailVO.propertyName +"','" + 
						themeDetailVO.values +"','" + 
						themeDetailVO.gradient1 +"','"+ 
						themeDetailVO.gradient2 +"','" +
						themeDetailVO.stroke +"','" +
						themeDetailVO.textColor+"','" +
						themeID+"')";
					
					executeHandler(query, iDataBaseManager);
					
				}
				
				
			}
			
		}
		
		/**
		 * @Param theme contain active theme details
		 * Insert active theme details into ACTIVE_THEME table
		 */ 
		private function insertActiveTheme(theme:ThemeVO1):void
		{
			
			var query:String;
			var iDataBaseManger:IDatabaseManager = new DataBaseManager();
			
			query = "INSERT INTO ACTIVE_THEME ( primary_color, secondary_color, label_color, at_secondary_label_color, at_background ) " + 
				"VALUES('"+ 
				theme.primaryColor +"','" + 
				theme.secondaryColor +"','" + 
				theme.lableColor +"','" +
				theme.secondaryLabelColor+"','" +
				theme.background+"')";
			
			try
			{
				
				iDataBaseManger.execute( query );
				
			} 
			catch(error:DataBaseError) 
			{
				
				throw error;
				trace("error -> ThemeManger.insertActiveTheme()");
				
			}
			
		}
		
		/**
		 * @Return true if themes table contain data
		 * 
		 */ 
		private function isThemesExist():Boolean
		{
			var themesExist:Boolean = false;
			var iDataBaseManger:IDatabaseManager;
			var arrThemes:ArrayCollection = new ArrayCollection();
			var query:String;
			
			try
			{
				
				query = "SELECT * FROM IM_THEMES";
				iDataBaseManger = new DataBaseManager();
				arrThemes = iDataBaseManger.getData(query);
				
			} 
			catch(error:DataBaseError) 
			{
				
				trace("error in -> ThemeManger.isThemesExist()");
				throw error;
				
			}
			
			if( arrThemes.length > 0 )
				themesExist = true;
			
			return themesExist;
			
		}
		
		/**
		 * This is the function for Delete a theme
		 * 
		 * @functionName deleteTheme
		 * @creationDate Aug 13, 2012
		 * @author micmac
		 * @params themeID:int
		 */
		public function deleteTheme(themeID:int):void
		{
			
			var iDataBaseManger:IDatabaseManager = new DataBaseManager();
			var query:String;
			
			iDataBaseManger.setTransactionStartPoint();
			
			query = "Delete FROM IM_THEME_DETAILS WHERE td_id='"+themeID+"'";
			executeHandler( query,  iDataBaseManger);
			
			query = "Delete FROM IM_THEMES WHERE th_id='"+themeID+"'";
			executeHandler( query, iDataBaseManger );
			
			iDataBaseManger.commitTransaction();
			
		}
		
		/**
		 * This is the function for edit theme detail
		 * 
		 * @functionName editTheme
		 * @creationDate Aug 13, 2012
		 * @author micmac
		 * @params themeVO:ThemeVO
		 */
		public function editTheme(iDatabaseManger:IDatabaseManager,themeVO:ThemeVO):void
		{
			
			var query:String;
			
			for each(var themeDetailVO:ThemeDetailVO in themeVO.arrThemeDetailVO)
			{
				
				query = "UPDATE IM_THEME_DETAILS SET value='"+themeDetailVO.values+"'," +
					"gradient1='"+themeDetailVO.gradient1+"'," +
					"gradient2='"+themeDetailVO.gradient2+"'," +
					"stroke='"+themeDetailVO.stroke+"'," +
					"text_color='"+themeDetailVO.textColor+"' WHERE td_id='"+themeVO.themeID+"' AND property_name='"+themeDetailVO.propertyName+"'";
				
				executeHandler(query, iDatabaseManger);
				
			}
			
			query = "UPDATE IM_THEMES SET th_active='"+themeVO.active+"'," +
				"th_creator='"+themeVO.creator+"' WHERE th_id='"+themeVO.themeID+"'";
			
			executeHandler(query, iDatabaseManger);
			
		}
		
		private static function retrieveHandler(val:String, dataBaseManger:IDatabaseManager = null):ArrayCollection
		{
			
			var result:ArrayCollection = new ArrayCollection();
			var _iDBManager:IDatabaseManager;
			
			if(dataBaseManger)
				_iDBManager = dataBaseManger;
			else
				_iDBManager = new DataBaseManager();
			
			try
			{
				
				result = _iDBManager.getData(val);
				
			} 
			catch(error:DataBaseError) 
			{
				
				trace("Application-retrieveHandler() : Database Read error");
				throw error;
				
			}
			
			return result;
			
		}
		
		private function executeHandler(val:String, iDataBaseManger:IDatabaseManager):void
		{
			
			try
			{
				
				iDataBaseManger.execute(val);
				
			} 
			catch(error:DataBaseError) 
			{
				
				iDataBaseManger.rollBackTransactions();
				trace("ApplicationStyleUpdator-executeHandler() : Database execution error");
				throw error;
				
			}
			
		}
		
		private function insertHandler(val:String, iDataBaseManger:IDatabaseManager):void
		{
			
			try
			{
				
				iDataBaseManger.insertValues(val);
				
			} 
			catch(error:DataBaseError) 
			{
				
				iDataBaseManger.rollBackTransactions();
				trace("ApplicationStyleUpdator-insertHandler() : Database insertion error");
				throw error;
				
			}
			
		}
		
		
		//Getters n Setters
		public function get localThemeVersion():String
		{
			return this._localThemeVersion;
		}
		public function set localThemeVersion(val:String):void
		{
			this._localThemeVersion = val;
		}
		
		public function get serverThemeVersion():String
		{
			return this._serverThemeVersion;
		}
		public function set serverThemeVersion(val:String):void
		{
			this._serverThemeVersion = val;
		}
		
	}
}